package com.library.weiget;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.jtjrenren.android.taxi.driver.R;

public class ViewEditText extends EditText implements OnFocusChangeListener {
    private Timer mTimer = new Timer();
    private TimerTask taskUpdateInputType;

    private final int WHAT_UPDATE_INPUT_TYPE = 101, WHAT_REGAIN_FOCUS = 102;

    private boolean finalized = false;
    private Context context;

    private String realText;

    private boolean customEllipsize;
    private boolean dropDown;

    private OnDropDownListener onDropDownListener;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (!finalized) {
                switch (msg.what) {
                    case WHAT_UPDATE_INPUT_TYPE:
                        refreshDrawables();

                        actionOnFocusChanged(ViewEditText.this,
                                ViewEditText.this.hasFocus());
                        break;
                    case WHAT_REGAIN_FOCUS:
                        if (ViewEditText.this.isFocused()) {
                            ViewEditText.this.clearFocus();
                            ViewEditText.this.requestFocus();
                        }
                        break;
                }
            }
        }

        ;
    };

    public ViewEditText(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

    }

    @Override
    protected void finalize() throws Throwable {
        // TODO Auto-generated method stub
        super.finalize();
        finalized = true;

        if (taskUpdateInputType != null) {
            taskUpdateInputType.cancel();
            taskUpdateInputType = null;
        }

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public ViewEditText(final Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

        this.setSingleLine();
        this.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        this.setText("");
        this.setInputType(this.getInputType());

        setOnFocusChangeListener(this);

        mHandler.sendEmptyMessageDelayed(WHAT_REGAIN_FOCUS, 200);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int DRAWABLE_LEFT = 0;
                final int DRAWABLE_TOP = 1;
                final int DRAWABLE_RIGHT = 2;
                final int DRAWABLE_BOTTOM = 3;

                if (event.getAction() == MotionEvent.ACTION_UP
                        && ViewEditText.this.getCompoundDrawables()[DRAWABLE_RIGHT] != null) {
                    boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight());

                    if (touchable) {

                        if (ViewEditText.this.getText().toString().length() > 0) {
                            ViewEditText.this.setText("");
                            return true;
                        } else {
                            if (dropDown) {
                                onDropDownListener.onDropDown();

                                return true;
                            }
                        }

                    }
                }

                return false;
            }
        });

        this.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (taskUpdateInputType != null) {
                    taskUpdateInputType.cancel();
                    taskUpdateInputType = null;
                }
                taskUpdateInputType = new TimerTask() {

                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(WHAT_UPDATE_INPUT_TYPE);
                    }
                };
                mTimer.schedule(taskUpdateInputType, 50);
            }
        });
    }

    private void refreshDrawables() {
        if (context != null) {
            Drawable drawableDel = context.getResources().getDrawable(
                    R.mipmap.icon_del);
            if (ViewEditText.this.getText().toString().length() == 0
                    || !ViewEditText.this.isEnabled()) {
                if (!dropDown) {
                    drawableDel = null;
                } else {
                    drawableDel = context.getResources().getDrawable(
                            R.mipmap.icon_arrow_down);
                }
            }
            Drawable[] drawable = this.getCompoundDrawables();
            this.setCompoundDrawablesWithIntrinsicBounds(drawable[0], null,
                    drawableDel, null);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        // TODO Auto-generated method stub
        super.setEnabled(enabled);

        refreshDrawables();
    }

    private void log(String msg) {
        Log.e(ViewEditText.this.getClass().getSimpleName(), msg);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // TODO Auto-generated method stub
        actionOnFocusChanged(v, hasFocus);
    }

    private void actionOnFocusChanged(View v, boolean hasFocus) {
        if (customEllipsize) {
            EditText et = (EditText) v;
            String end = "...";
            if (hasFocus) {
                et.setEllipsize(TruncateAt.END);

                if (et.getText().toString().endsWith(end)) {
                    et.setText(realText);
                    et.setSelection(realText.length());
                }
            } else {
                et.setEllipsize(TruncateAt.START);

                realText = et.getText().toString();
                if (realText.length() > 10) {
                    et.setText(realText.substring(0, 10) + end);
                }
            }
        }
    }

    public void setOnDropDownListener(OnDropDownListener listener) {
        onDropDownListener = listener;
    }

    public interface OnDropDownListener {
        public void onDropDown();
    }

    public void setCustomEllipsize() {
        // TODO Auto-generated method stub
        customEllipsize = true;
    }

    public void setDropDown() {
        dropDown = true;
    }
}